<script setup lang="ts">
definePageConfig({
  navigationBarTitleText: '人脸验证'
});

import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue';
// import { useRouter } from 'vue-router';
import { useToast } from '@/composables';
import { verifyFace } from '@/service/api/auth';

// const router = useRouter();
const toast = useToast();

const videoRef = ref<HTMLVideoElement | null>(null);
const canvasRef = ref<HTMLCanvasElement | null>(null);
const captureBtnRef = ref<HTMLButtonElement | null>(null);
const retryBtnRef = ref<HTMLButtonElement | null>(null);
const confirmBtnRef = ref<HTMLButtonElement | null>(null);

const isLoading = ref(false);
const isVerifying = ref(false);
const hasCaptured = ref(false);
const capturedImage = ref('');

// 相机流对象
let stream: MediaStream | null = null;

// 初始化摄像头
const initCamera = async () => {
  try {
    if (!videoRef.value) return;
    
    // 获取用户媒体设备
    stream = await navigator.mediaDevices.getUserMedia({
      video: {
        facingMode: 'user', // 使用前置摄像头
        width: { ideal: 1280 },
        height: { ideal: 720 }
      }
    });
    
    videoRef.value.srcObject = stream;
    
    // 等待视频元数据加载完成
    await new Promise((resolve) => {
      videoRef.value!.onloadedmetadata = () => {
        videoRef.value!.play();
        resolve(true);
      };
    });
  } catch (error: any) {
    toast.error('无法访问摄像头，请确保已授予相机权限');
    console.error('摄像头初始化失败:', error);
  }
};

// 拍摄照片
const captureImage = () => {
  if (!videoRef.value || !canvasRef.value) return;
  
  const video = videoRef.value;
  const canvas = canvasRef.value;
  
  // 设置画布尺寸与视频相同
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  
  // 绘制当前视频帧到画布
  const ctx = canvas.getContext('2d');
  if (ctx) {
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    
    // 将画布内容转换为base64格式的图片
    capturedImage.value = canvas.toDataURL('image/jpeg', 0.8);
    hasCaptured.value = true;
    
    // 暂停视频流
    if (stream) {
      stream.getTracks().forEach(track => track.enabled = false);
    }
  }
};

// 重新拍摄
const retryCapture = () => {
  hasCaptured.value = false;
  capturedImage.value = '';
  
  // 恢复视频流
  if (stream) {
    stream.getTracks().forEach(track => track.enabled = true);
  }
};

// 提交验证
const submitVerification = async () => {
  if (!capturedImage.value || isVerifying.value) return;
  
  try {
    isVerifying.value = true;
    toast.loading('验证中...');
    
    // 调用API进行人脸验证
    const res = await verifyFace(capturedImage.value);
    
    if (res.code === 0) {
      toast.success('人脸验证成功');
      // 延迟后返回上一页
      setTimeout(() => {
        // router.back();
      }, 1500);
    } else {
      toast.error(res.message || '人脸验证失败，请重试');
    }
  } catch (error: any) {
    toast.error(error.message || '人脸验证失败，请稍后再试');
  } finally {
    isVerifying.value = false;
  }
};

// 组件挂载后初始化
onMounted(async () => {
  await initCamera();
});

// 组件卸载时释放资源
const onUnmounted = () => {
  if (stream) {
    stream.getTracks().forEach(track => track.stop());
    stream = null;
  }
};
</script>

<template>
  <basic-layout>
    <view class="bg-white min-h-screen">
      <!-- 提示信息 -->
      <view class="bg-blue-50 border-l-4 border-blue-400 p-4 rounded-r my-4">
        <view class="flex items-start">
          <view class="i-local-info-circle text-blue-500 mt-0.5"></view>
          <view class="ml-2 text-sm text-blue-700">
            请确保光线充足，面部清晰可见，不要佩戴眼镜或口罩
          </view>
        </view>
      </view>
      
      <!-- 相机预览区域 -->
      <view class="relative mx-4 mb-6">
        <view class="aspect-[4/3] bg-gray-100 rounded-xl overflow-hidden">
          <video 
            v-if="!hasCaptured"
            ref="videoRef"
            class="w-full h-full object-cover"
            autoplay
            muted
            playsinline
          ></video>
          
          <image 
            v-else
            :src="capturedImage"
            class="w-full h-full object-cover"
            alt="已拍摄人脸照片"
          ></image>
          
          <!-- 人脸框提示 -->
          <view 
            v-if="!hasCaptured"
            class="absolute inset-0 flex items-center justify-center pointer-events-none"
          >
            <view class="w-4/5 h-3/5 border-2 border-blue-400 rounded-2xl"></view>
          </view>
        </view>
        
        <!-- 拍摄按钮 -->
        <view v-if="!hasCaptured" class="absolute bottom-4 left-1/2 transform -translate-x-1/2">
          <nut-button 
            type="primary" 
            size="large"
            @click="captureImage"
            ref="captureBtnRef"
            class="w-20 h-20 rounded-full flex items-center justify-center"
          >
            <view class="i-local-camera text-2xl"></view>
          </nut-button>
        </view>
        
        <!-- 重拍和确认按钮 -->
        <view v-else class="absolute bottom-4 left-0 right-0 flex justify-center space-x-4">
          <nut-button 
            type="default" 
            size="large"
            @click="retryCapture"
            ref="retryBtnRef"
            class="flex-1 max-w-[140px]"
          >
            重拍
          </nut-button>
          <nut-button 
            type="primary" 
            size="large"
            @click="submitVerification"
            :loading="isVerifying"
            ref="confirmBtnRef"
            class="flex-1 max-w-[140px]"
          >
            确认提交
          </nut-button>
        </view>
      </view>
      
      <!-- 验证指南 -->
      <view class="mx-4 mb-6">
        <view class="text-lg font-medium mb-2">人脸验证指南</view>
        <view class="space-y-3">
          <view class="flex items-start">
            <view class="text-blue-500 mt-0.5">1.</view>
            <view class="ml-2 text-sm">请将面部正对摄像头，保持表情自然</view>
          </view>
          <view class="flex items-start">
            <view class="text-blue-500 mt-0.5">2.</view>
            <view class="ml-2 text-sm">确保光线充足，避免逆光或阴影</view>
          </view>
          <view class="flex items-start">
            <view class="text-blue-500 mt-0.5">3.</view>
            <view class="ml-2 text-sm">请勿佩戴眼镜、口罩、帽子等遮挡物</view>
          </view>
          <view class="flex items-start">
            <view class="text-blue-500 mt-0.5">4.</view>
            <view class="ml-2 text-sm">请保持面部在取景框内</view>
          </view>
        </view>
      </view>
    </view>
  </basic-layout>
</template>  